# FastAPI的相关模块导入
from fastapi import FastAPI, Form, File, UploadFile, Request, Response
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware

# 导入数据库orm模块
from tortoise.contrib.fastapi import register_tortoise

#
from pydantic import BaseModel, Field, ValidationError, validator, validators, EmailStr

#
from typing import Union, List, Optional
import uvicorn
from datetime import date
import sys
import os
from settings import TORTOISE_ORM

# 导入app子应用
from apps.app01.urls import shop
from apps.app02.urls import user
from apps.student.urls import student



app = FastAPI()
templates = Jinja2Templates(directory="templates") # 实例化Jinja2对象，并将文件夹路径设置为以templates名称的文件夹
# fastapi一旦运行, register_tortoise已经执行, 实现监控
register_tortoise(
    app=app,
    config=TORTOISE_ORM,
    # generate_schemas=True,  # 如果数据库为空, 则自动生成对应表单, 生产环境不要开启这个选项
    # add_exception_handlers=True,    # 生产环境不要开启这个选项, 这个是调试信息打印
)

app.include_router(shop, prefix="/shop", tags=["购物中心接口"])
app.include_router(user, prefix="/user", tags=["用户中心接口"])
app.include_router(student, prefix="/student", tags=["学生管理接口"])



# @app.middleware("http")
# async def CORSMiddleware(request: Request, call_next):
#     response = await call_next(request)
#     response.headers["Access-Control-Allow-Origin"] = "*"
#     return response

origins = [
    "http://localhost:63342"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins="*",  # *：代表所有客户端
    allow_credentials=True,
    allow_methods=["GET", "POST"],
    allow_headers=["*"],
)


@app.middleware("http")
async def middleware_2(request: Request, call_next):
    # 请求代码块
    print("middleware_2 request")

    response = await call_next(request)

    # 响应代码块
    print("middleware_2 response")

    return response


@app.middleware("http")
async def middleware_1(request: Request, call_next):
    # 请求代码块
    print("middleware_1 request")
    if request.client.host in ["127.0.0.1", ]:
        return Response(status_code=1001, content="非法请求")

    response = await call_next(request)

    # 响应代码块
    print("middleware_1 response")

    return response


if __name__ == '__main__':
    print(sys.argv)

    # 获取当前文件的完整路径
    file_path = __file__
    # 获取文件名
    file_name = os.path.basename(file_path)
    print(file_name)

    start_args = file_name.split(".py")[0] + ":app"

    # 等同于：uvicorn.run("manage:app", host="127.0.0.1", port=8000, reload=True)
    uvicorn.run(start_args, host="127.0.0.1", port=8000, reload=True)